package com.imooc.sell.converter;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.imooc.sell.Enums.ResultEnum;
import com.imooc.sell.dataobject.OrderDetail;
import com.imooc.sell.dto.OrderDto;
import com.imooc.sell.exception.SellException;
import com.imooc.sell.from.OrderFrom;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author 小柯
 * @Date 2019/7/7  12:20
 **/
@Slf4j
public class OrserFrom2OrderVo {


    public static OrderDto convert(OrderFrom orderFrom){
        Gson gson = new Gson();

        OrderDto orderDto = new OrderDto();
        //BeanUtils.copyProperties(orderFrom, orderDto);
        orderDto.setBuyerName(orderFrom.getName());
        orderDto.setBuyerPhone(orderFrom.getPhone());
        orderDto.setBuyerAddress(orderFrom.getAddress());
        orderDto.setBuyerOpenid(orderFrom.getOpenid());

        List<OrderDetail> orderDetailList = new ArrayList<>();
        try{
            //将 orderFrom.getItems() 通过成Json  <List<OrderDetail>
            orderDetailList = gson.fromJson(orderFrom.getItems(), new TypeToken<List<OrderDetail>>(){}.getType());

        }catch (Exception e){
            log.error("【对象转换错误】,json={}", orderDto );
            throw new SellException(ResultEnum.PRODUCT_PARAMETER_ERROR);

        }
        orderDto.setOrderDetailList(orderDetailList);

        return orderDto;
    }




}
